/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-02 18:14:25
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-04-23 17:48:20
 */
const commonRes = require('../utils/commonRes')
const { getKey, setKey } = require('../utils/fileDb')
const { sm4Encrypt, sm4Decrypt } = require('../utils/index')

class SiteManage {

  static async sitelist(req, res) {
    let data = getKey('siteRes')
    data.forEach(site => site.cookie = sm4Decrypt(site.cookie))
    commonRes(res, data)
  }

  static async siteadd(req, res) {
    let data = req.body
    if (!data.siteName) return commonRes(res, null, { message: '站点名称不能为空', status: 'error' })
    if (!data.cookie) return commonRes(res, null, { message: 'cookie不能为空', status: 'error' })
    if (!(data.plates && data.plates.length)) return commonRes(res, null, { message: '至少添加1个板块', status: 'error' })

    // 更新或添加数据
    let siteData = getKey('siteRes') || []
    data.cookie = sm4Encrypt(data.cookie)
    let updateIndex = siteData.findIndex(item => item.sid === data.sid)
    if (updateIndex !== -1) {
      siteData.splice(updateIndex, 1, data)
    } else {
      siteData.push(data)
    }
    // 根据sort排序
    siteData.sort((a, b) => (a.sort - b.sort > 0) ? 1 : -1)
    siteData.forEach(item => item.plates.sort((a, b) => (a.sort - b.sort > 0) ? 1 : -1))

    setKey('siteRes', siteData)
    commonRes(res, null, { message: '操作成功' })
  }

  static async sitedel(req, res) {
    let sid = req.query.sid
    let siteData = getKey('siteRes') || []
    let newSiteData = siteData.filter(site => site.sid != sid)
    newSiteData.forEach((site, j) => {
      site.sort = j + 1 + ''
    })
    setKey('siteRes', newSiteData)
    commonRes(res, null, { message: '删除成功' })
  }
}

module.exports = SiteManage